<?php

namespace App\Http\Controllers\Api;

use App\Utils\ErrCode;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class AuthController extends ApiController
{
    public function __construct()
    {
        $this->middleware('token.refresh', ['except' => ['login','refresh']]);
    }
    /*
     * 后台api登录
     * @param Request $request
     */
    public function login(Request $request): JsonResponse
    {
        try {
            $this->validateLogin($request);

            if ($this->attemptLogin($request)) {
                return $this->respondWithToken($request);
            }

            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e);
        }
    }

    /**
     * @param Request $request
     * @throws Exception
     */
    protected function validateLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            throw new Exception('请输入账号或密码', ErrCode::USERNAME_PASSWORD_ERR);
        }
    }

    /**
     * @return string
     */
    public function username(): string
    {
        return 'username';
    }

    /**
     * @param Request $request
     * @return bool
     */
    protected function attemptLogin(Request $request): bool
    {
        return $this->guard()->attempt(
            $this->credentials($request)
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param Request $request
     * @return array
     */
    protected function credentials(Request $request): array
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * @return \Illuminate\Contracts\Auth\Factory|\Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard|\Illuminate\Contracts\Foundation\Application
     */
    protected function guard()
    {
        return auth('api');
    }

    /**
     * 用户信息
     *
     * @return JsonResponse
     */
    public function userinfo(): JsonResponse
    {
        return $this->success($this->guard()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return JsonResponse
     */
    public function refresh(): JsonResponse
    {
        return $this->respondWithToken($this->guard()->refresh());
    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    protected function respondWithToken(Request $request): JsonResponse
    {
        $token = $this->guard()->getToken()->get();
        $user = $this->guard()->user();

        return $this->success([
            'user' => $user,
            'token' => $token
        ]);
    }
}
